import 'dart:convert' as convert;
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'Door.dart';

class IndexPages extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _IndexPagesState();
}

class _IndexPagesState extends State<IndexPages> {
  LightBeltone(data) {
    return Stack(
      overflow: Overflow.visible,
      children: <Widget>[
        Container(
          child: Image.asset('images/电视_0029.png'),
        ),
        Positioned(
          left: mediaQuery.size.width / 25,
          top: mediaQuery.size.height / 50,
          child: Container(
            child: Image.asset(
              'images/灯带_0026.png',
              width: mediaQuery.size.width / 5.5,
            ),
          ),
        ),
        Positioned(
          left: mediaQuery.size.width / 2.7,
          top: mediaQuery.size.height / 800,
          child: GestureDetector(
              child: Image.asset(
                date[data]['status'] == '0xff000000'
                    ? 'images/off.png'
                    : 'images/on.png',
                width: mediaQuery.size.width / 15,
              ),
              onTap: () {
                setState(() {
                  pickerColor = Color(
                      _hexToInt(date[data]['status'].toString().substring(2)));
                });
                pickColor(data);
              }),
        ),
        Positioned(
          left: mediaQuery.size.width / 2.7,
          top: mediaQuery.size.height / 26,
          child: GestureDetector(
              child: Image.asset(
                date[data]['status'] == '0xff000000'
                    ? 'images/off.png'
                    : 'images/on.png',
                width: mediaQuery.size.width / 15,
              ),
              onTap: () {
                Message('rf/iotgw/' + date[data]['ornate'] + '/set',
                    '0x01 0x05 0x09 0x00 0xff');
              }),
        ),
        Positioned(
          left: mediaQuery.size.width / 2.7,
          top: mediaQuery.size.height / 13,
          child: GestureDetector(
              child: Image.asset(
                date[data]['status'] == '0xff000000'
                    ? 'images/off.png'
                    : 'images/on.png',
                width: mediaQuery.size.width / 15,
              ),
              onTap: () {
                Message('rf/iotgw/' + date[data]['ornate'] + '/set',
                    '0x02 0x06 0x10 0x10 0xff');
              }),
        ),
        Positioned(
          left: mediaQuery.size.width / 4,
          top: mediaQuery.size.height / 60,
          child: Container(
            child: new Text(
              '颜色',
              style: TextStyle(
                  fontFamily: '黑体',
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: Colors.black),
            ),
          ),
        ),
        Positioned(
          left: mediaQuery.size.width / 4,
          top: mediaQuery.size.height / 18,
          child: Container(
            child: new Text(
              '呼吸',
              style: TextStyle(
                  fontFamily: '黑体',
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: Colors.black),
            ),
          ),
        ),
        Positioned(
          left: mediaQuery.size.width / 4,
          top: mediaQuery.size.height / 10.5,
          child: Container(
            child: new Text(
              '爆闪',
              style: TextStyle(
                  fontFamily: '黑体',
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: Colors.black),
            ),
          ),
        ),
      ],
    );
  }

  late List<Map<String, dynamic>> date = [
    {'name': 'tg1', 'status': 'off', 'ornate': 'hx1'},
    {'name': 'tg2', 'status': 'off', 'ornate': 'hx2'},
    {'name': 'tg3', 'status': 'off', 'ornate': 'hx3'},
    {'name': 'tg4', 'status': 'off', 'ornate': 'hx4'},
    {'name': 'tg5', 'status': 'off', 'ornate': 'hx5'}
  ];
  late List<Map<String, dynamic>> bate = [
    {'name': 'k01', 'status': 'off', 'nickName': '西墙电视'},
    {'name': 'k02', 'status': 'off', 'nickName': '北墙1号电视'},
    {'name': 'k03', 'status': 'off', 'nickName': '北墙2号电视'},
    {'name': 'k04', 'status': 'off', 'nickName': '北墙3号电视'},
    {'name': 'k05', 'status': 'off', 'nickName': '北墙4号电视'},
    {'name': 'k06', 'status': 'off', 'nickName': '东墙大屏1,5'},
    {'name': 'k07', 'status': 'off', 'nickName': '东墙大屏2,6'},
    {'name': 'k08', 'status': 'off', 'nickName': '东墙大屏3,7'},
    {'name': 'k09', 'status': 'off', 'nickName': '东墙大屏4,8'},
    {'name': 'k10', 'status': 'off', 'nickName': '护眼灯南路'},
    {'name': 'k11', 'status': 'off', 'nickName': '护眼灯北路'},
    {'name': 'k12', 'status': 'off', 'nickName': '南墙灯箱'},
    {'name': 'k13', 'status': 'off', 'nickName': '筒灯'},
    {'name': 'k14', 'status': 'off', 'nickName': '内层射灯'},
    {'name': 'k15', 'status': 'off', 'nickName': '无'},
    {'name': 'k16', 'status': 'off', 'nickName': '东墙LED屏'}
  ];
  MqttServerClient client =
      MqttServerClient.withPort('192.168.100.230', '001', 1883);

  //初始化电视按钮状态
  Future<void> watchStatus() async {

    for(var i = 0;i< bate.length;i++){
      Message('rf/iotgw/k0'+(i+1).toString()+'/get', '');
      await Future.delayed(Duration(milliseconds: 200),(){
        bate[i]['status'] = status == "" ? 'off' : status;
      });
      Future.delayed(Duration(milliseconds: 500), () {
        Message('rf/iotgw/tg1/get', '0x04');
        date[0]['status'] = SixtoColor( status == '' ? '0xff000000' : status);
        setState(() {
          date = date;
        });
      });
    }
  }

  //初始化
  @override
  void initState() {
    //设置mqtt参连接相关参数
    client.onConnected = onConnected; //连接成功回调
    client.onDisconnected = onDisconnected; //连接断开回调
    client.onSubscribed = onSubscribed; //订阅成功回调
    client.onSubscribeFail = onSubscribeFail; //订阅失败回调
    client.onUnsubscribed = onUnsubscribed as UnsubscribeCallback?; //取消订阅回调
    client.pongCallback = pong; //收到 PING 响应回调
    client.logging(on: false); //设置是否登陆
    client.connect();
    super.initState();
    Future.delayed(Duration(seconds: 2), () {
      watchStatus(); //连接，这里不需要异步
    });

  }

  //消息监听
  void Message(zt, xx) async {
    var bate = this.client.getSubscriptionsStatus("rf/#");
    if (bate.toString().indexOf('active') == -1) {
      //订阅主题
      await this.client.subscribe("rf/#", MqttQos.exactlyOnce);
    }
    //消息发布
    // const pubTopic = 'chenhaiwei'; //发布消息的主题
    final builder = MqttClientPayloadBuilder();
    builder.addString(xx); //发布的内容
    await client.publishMessage(zt, MqttQos.exactlyOnce, builder.payload);

    //取消订阅
    client.onUnsubscribed(zt);

    //监听消息
    client.updates!.listen((List<MqttReceivedMessage<MqttMessage?>>? c) {
      var recMess = c![0].payload as MqttPublishMessage;
      var pt =  MqttPublishPayload.bytesToStringAsString(recMess.payload.message!);

      setState(() {
        status = pt;
      });
      // log('消息:$pt,主题: <${c[0].topic}>');
    });
  }

  //页面销毁时关闭连接
  @override
  void dispose() {
    client.onDisconnected(); //断开连接
    super.dispose();
  }

  late String status = '';

  int _index = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        //这里设置
        backgroundColor: Color(0xFFECECE8),
        appBar: AppBar(
          title: Text('我的会议室', style: TextStyle(color: Colors.black)),
          backgroundColor: Color(0xFFD0D0CD),
          //后面放置图标
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.help),
              onPressed: () {},
            ),
            IconButton(
              icon: Icon(Icons.settings),
              onPressed: () {},
            ),
          ],
        ),
        drawer: Drawer(
          child: Column(
            children: <Widget>[
              //头部
              Row(
                children: <Widget>[
                  Expanded(
                    child: DrawerHeader(
                      child: Text("我的会议室"),
                      decoration: BoxDecoration(
                          image: DecorationImage(
                              image: NetworkImage(
                                  "https://www.itying.com/images/flutter/2.png"),
                              fit: BoxFit.cover)),
                    ),
                  )
                ],
              ),
              ListTile(
                leading: CircleAvatar(
                  child: Icon(Icons.tv),
                ),
                title: Text("电视"),
                onTap: () {
                  Navigator.of(context, rootNavigator: true).pop();
                  setState(() {
                    _index = 0;
                  });
                },
              ),
              Divider(),
              ListTile(
                leading: CircleAvatar(
                  child: Icon(Icons.tablet),
                ),
                title: Text("LED灯带"),
                onTap: () {
                  Navigator.of(context, rootNavigator: true).pop();
                  setState(() {
                    _index = 1;
                  });
                },
              ),
              Divider(),
              ListTile(
                leading: CircleAvatar(
                  child: Icon(Icons.smart_button),
                ),
                title: Text("智能家居"),
                onTap: () {
                  Navigator.of(context, rootNavigator: true).pop();
                  setState(() {
                    _index = 2;
                  });
                },
              ),
              Divider(),
            ],
          ),
        ),
        body: _index == 0
            ? Watch()
            : _index == 1
                ? LightBelt()
                : Door());
  }

  @override
  Widget LightBelt() {
    return Wrap(children: <Widget>[
      Stack(
        alignment: AlignmentDirectional.center,
        children: <Widget>[
          Container(
            alignment: Alignment.topLeft,
            child: Image.asset('images/灯带_0001.png',
                width: MediaQuery.of(context).size.width / 1.3,
                height: MediaQuery.of(context).size.height / 8),
          ),
          Container(
            alignment: Alignment(-0.5, 0.0),
            child: Text('LED灯带',
                style: TextStyle(color: Colors.white, fontSize: 18)),
          ),
        ],
      ),
      Container(
          width: MediaQuery.of(context).size.width,
          height: (MediaQuery.of(context).size.height / 9.45) * 7,
          child: GridView.count(
            shrinkWrap: true,
            crossAxisCount: 2,
            mainAxisSpacing: 10,
            crossAxisSpacing: 10,
            childAspectRatio: 1.8,
            children: [
              LightBeltone(0),
              LightBeltone(1),
              LightBeltone(2),
              LightBeltone(3),
              LightBeltone(4),
            ],
          )),
    ]);
  }

  int _hexToInt(String hex) {
    int val = 0;
    int len = hex.length;
    for (int i = 0; i < len; i++) {
      int hexDigit = hex.codeUnitAt(i);
      if (hexDigit >= 48 && hexDigit <= 57) {
        val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 65 && hexDigit <= 70) {
        // A..F
        val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 97 && hexDigit <= 102) {
        // a..f
        val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
      } else {
        throw new FormatException("Invalid hexadecimal value");
      }
    }
    return val;
  }

  // create some values
  Color pickerColor = Color(0xff443a49);
  Color currentColor = Color(0xff443a49);

// ValueChanged<Color> callback
  void changeColor(Color color) {
    setState(() => pickerColor = color);
  }

  List<Color> currentColors = [Colors.limeAccent, Colors.green];

  // raise the [showDialog] widget
  void changeColors(List<Color> colors) =>
      setState(() => currentColors = colors);

  //颜色选择器
  void pickColor(data) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('选择灯带颜色！'),
          content: SingleChildScrollView(
            // child: ColorPicker(
            //   pickerColor: pickerColor,
            //   onColorChanged: changeColor,
            //   showLabel: true,
            //   pickerAreaHeightPercent: 0.8,
            // ),
            // Use Material color picker:
            //
            // child: MaterialPicker(
            //   pickerColor: pickerColor,
            //   onColorChanged: changeColor,
            //   enableLabel: true,
            // ),
            //
            // Use Block color picker:
            //
            child: BlockPicker(
              pickerColor: currentColor,
              onColorChanged: changeColor,
            ),

            // child: MultipleChoiceBlockPicker(
            //   pickerColors: currentColors,
            //   onColorsChanged: changeColors,
            // ),
          ),
          actions: <Widget>[
            FlatButton(
              child: const Text('默认'),
              onPressed: () {
                Message('rf/iotgw/' + date[data]['name'] + '/set',
                    '0xff 0xff 0xff 0xff');
                setState(() => currentColor = pickerColor);
                Navigator.of(context).pop();
                if (status != "") {
                  LEDshowToastOnSuccess(date[data]['nickName']);
                } else {
                  LEDshowToastOnFail(date[data]['nickName']);
                }
              },
            ),
            FlatButton(
              child: const Text('确定'),
              onPressed: () {
                Message('rf/iotgw/' + date[data]['name'] + '/set',
                    ColortoSix('0x' + pickerColor.value.toRadixString(16)));
                setState(() => currentColor = pickerColor);
                Navigator.of(context).pop();
                if (status != "") {
                  LEDshowToastOnSuccess(date[data]['nickName']);
                } else {
                  LEDshowToastOnFail(date[data]['nickName']);
                }
              },
            ),
            FlatButton(
              child: const Text('取消'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  late double _sliderValue = 0;

  //呼吸灯选择器
  void pickBreathingLamp(data) {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('提示'),
            content: Slider(
              value: _sliderValue,
              label: '$_sliderValue',
              min: 0,
              max: 255,
              divisions: 20,
              onChanged: (v) {
                setState(() {
                  _sliderValue = v;
                });
              },
            ),
            actions: <Widget>[],
          );
        });
  }

//爆闪灯选择器
  void pickFlashLamp(data) {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
              title: const Text('选择爆闪灯参数'), content: SingleChildScrollView());
        });
  }

  //查询过来的十六进制转换为颜色
  String SixtoColor(data) {
    var color = '';
    List<String> strs = data.split(' ');
    for (int i = 0; i <= 3; i++) {
      if (color.length == 0) {
        color = strs[i].substring(2);
      } else {
        if (i == 3) {
          color =
              (strs[i].substring(2).length == 1 ? '00' : strs[i].substring(2)) +
                  color;
        } else {
          color = color +
              (strs[i].substring(2).length == 1 ? '00' : strs[i].substring(2));
        }
      }
    }
    return '0x' + color;
  }

  //将颜色转换为十六进制颜色
  String ColortoSix(data) {
    var x = '0x';
    var color = data.toString().substring(2);
    var one = color.substring(0, 2);
    var two = color.substring(2, 4);
    var three = color.substring(4, 6);
    var four = color.substring(6, 8);
    return x + two + ' ' + x + three + ' ' + x + four + ' ' + x + one;
  }

  @override
  Widget Watch() {
    return Wrap(children: <Widget>[
      Wrap(
        alignment: WrapAlignment.start,
        children: <Widget>[
          Image.asset('images/电视_03.png',
              width: MediaQuery.of(context).size.width / 1.3,
              height: MediaQuery.of(context).size.height / 8),
        ],
      ),
      Container(
          width: MediaQuery.of(context).size.width,
          height: (MediaQuery.of(context).size.height / 9.45) * 7,
          child: GridView.count(
            shrinkWrap: true,
            crossAxisCount: 2,
            mainAxisSpacing: 10,
            crossAxisSpacing: 10,
            childAspectRatio: 1.8,
            children: [
              _createGridViewItem1(),
              _createGridViewItem2(),
              _createGridViewItem3(0),
              _createGridViewItem4(1),
              _createGridViewItem3(2),
              _createGridViewItem4(3),
              _createGridViewItem3(4),
              _createGridViewItem4(5),
              _createGridViewItem3(6),
              _createGridViewItem4(7),
              _createGridViewItem3(8),
              _createGridViewItem4(9),
              _createGridViewItem3(10),
              _createGridViewItem4(11),
              _createGridViewItem3(12),
              _createGridViewItem4(13),
              _createGridViewItem3(14),
              _createGridViewItem4(15),
            ],
          )),
    ]);
  }

  final MediaQueryData mediaQuery = MediaQueryData.fromWindow(window);

  _createGridViewItem88(bate) {
    return GestureDetector(
      child: Image.asset('images/电视_07.png'),
      onTap: () {
        if (bate[bate]['status'] == 'off') {
          bate[bate]['status'] = 'on';
        } else {
          bate[bate]['status'] = 'off';
        }
        setState(() {});
      },
    );
  }



  _createGridViewItem1() {
    return GestureDetector(
      child: Image.asset('images/电视_07.png'),
      onTap: () {

        Future.delayed(Duration(seconds: 2), () {
          Message('rf/iotgw/k01/set', 'on'); bate[1]['status'] = 'on';
          Future.delayed(Duration(seconds: 2), () {
            Message('rf/iotgw/k02/set', 'on');bate[2]['status'] = 'on';
            Future.delayed(Duration(seconds: 2), () {
              Message('rf/iotgw/k03/set', 'on');bate[3]['status'] = 'on';
              Future.delayed(Duration(seconds: 2), () {
                Message('rf/iotgw/k04/set', 'on');bate[4]['status'] = 'on';
                Future.delayed(Duration(seconds: 2), () {
                  Message('rf/iotgw/k05/set', 'on');bate[5]['status'] = 'on';
                  Future.delayed(Duration(seconds: 2), () {
                    Message('rf/iotgw/k06/set', 'on');bate[6]['status'] = 'on';
                    Future.delayed(Duration(seconds: 2), () {
                      Message('rf/iotgw/k07/set', 'on');bate[7]['status'] = 'on';
                      Future.delayed(Duration(seconds: 2), () {
                        Message('rf/iotgw/k08/set', 'on');bate[8]['status'] = 'on';
                        Future.delayed(Duration(seconds: 2), () {
                          Message('rf/iotgw/k09/set', 'on');bate[9]['status'] = 'on';
                          Future.delayed(Duration(seconds: 2), () {
                            Message('rf/iotgw/k10/set', 'on');bate[10]['status'] = 'on';
                            Future.delayed(Duration(seconds: 2), () {
                              Message('rf/iotgw/k11/set', 'on');bate[11]['status'] = 'on';
                              Future.delayed(Duration(seconds: 2), () {
                                Message('rf/iotgw/k12/set', 'on');bate[12]['status'] = 'on';
                                Future.delayed(Duration(seconds: 2), () {
                                  Message('rf/iotgw/k13/set', 'on');bate[13]['status'] = 'on';
                                  Future.delayed(Duration(seconds: 2), () {
                                    Message('rf/iotgw/k14/set', 'on');bate[14]['status'] = 'on';
                                    Future.delayed(Duration(seconds: 2), () {
                                      Message('rf/iotgw/k15/set', 'on');bate[15]['status'] = 'on';
                                      Future.delayed(Duration(seconds: 2), () {
                                        Message('rf/iotgw/k16/set', 'on');bate[16]['status'] = 'on';
                                        showDialog(
                                            context: context,
                                            builder: (context) {
                                              return AlertDialog(
                                                title: Text("提示"),
                                                content: Text('电视启动完毕！请查看'),
                                                actions: <Widget>[
                                                  FlatButton(
                                                    child: Text("确认"),
                                                    onPressed: () {
                                                      Navigator.of(context)
                                                          .pop(true);//关闭对话框
                                                      setState(() {

                                                      });
                                                    },
                                                  )
                                                ],
                                              );
                                            });
                                      });
                                    });
                                  });
                                });
                              });
                            });
                          });
                        });
                      });
                    });
                  });
                });
              });
            });
          });
        });
      },
    );
  }



  _createGridViewItem2() {
    return GestureDetector(
      child: Image.asset('images/电视_09.png'),
      onTap: () async {
        for(var i = 1;i<16;i++){
          Future.delayed(Duration(seconds:2));
          Message('rf/iotgw/k0${i}/set', 'off');bate[i]['status'] = 'off';
        }


        Future.delayed(Duration(seconds: 2), () {
          Message('rf/iotgw/k01/set', 'off');bate[1]['status'] = 'off';
          Future.delayed(Duration(seconds: 2), () {
            Message('rf/iotgw/k02/set', 'off');bate[2]['status'] = 'off';
            Future.delayed(Duration(seconds: 2), () {
              Message('rf/iotgw/k03/set', 'off');bate[3]['status'] = 'off';
              Future.delayed(Duration(seconds: 2), () {
                Message('rf/iotgw/k04/set', 'off');bate[4]['status'] = 'off';
                Future.delayed(Duration(seconds: 2), () {
                  Message('rf/iotgw/k05/set', 'off');bate[5]['status'] = 'off';
                  Future.delayed(Duration(seconds: 2), () {
                    Message('rf/iotgw/k06/set', 'off');bate[6]['status'] = 'off';
                    Future.delayed(Duration(seconds: 2), () {
                      Message('rf/iotgw/k07/set', 'off');bate[7]['status'] = 'off';
                      Future.delayed(Duration(seconds: 2), () {
                        Message('rf/iotgw/k08/set', 'off');bate[8]['status'] = 'off';
                        Future.delayed(Duration(seconds: 2), () {
                          Message('rf/iotgw/k09/set', 'off');bate[9]['status'] = 'off';
                          Future.delayed(Duration(seconds: 2), () {
                            Message('rf/iotgw/k10/set', 'off');bate[10]['status'] = 'off';
                            Future.delayed(Duration(seconds: 2), () {
                              Message('rf/iotgw/k11/set', 'off');bate[11]['status'] = 'off';
                              Future.delayed(Duration(seconds: 2), () {
                                Message('rf/iotgw/k12/set', 'off');bate[12]['status'] = 'off';
                                Future.delayed(Duration(seconds: 2), () {
                                  Message('rf/iotgw/k13/set', 'off');bate[13]['status'] = 'off';
                                  Future.delayed(Duration(seconds: 2), () {
                                    Message('rf/iotgw/k14/set', 'off');bate[14]['status'] = 'off';
                                    Future.delayed(Duration(seconds: 2), () {
                                      Message('rf/iotgw/k15/set', 'off');bate[15]['status'] = 'off';
                                      Future.delayed(Duration(seconds: 2), () {
                                        Message('rf/iotgw/k16/set', 'off');bate[16]['status'] = 'off';
                                        showDialog(
                                            context: context,
                                            builder: (context) {
                                              return AlertDialog(
                                                title: Text("提示"),
                                                content: Text('电视关闭完毕！请查看'),
                                                actions: <Widget>[
                                                  FlatButton(
                                                    child: Text("确认"),
                                                    onPressed: () {
                                                      Navigator.of(context)
                                                          .pop(true); //关闭对话框
                                                      setState(() {

                                                      });
                                                    },
                                                  )
                                                ],
                                              );
                                            });
                                      });
                                    });
                                  });
                                });
                              });
                            });
                          });
                        });
                      });
                    });
                  });
                });
              });
            });
          });
        });
        ;
      },
    );
  }

  _createGridViewItem3(datas) {
    return Stack(
      overflow: Overflow.visible,
      children: <Widget>[
        Container(
          child: Image.asset('images/电视_0029.png'),
        ),
        Positioned(
          left: mediaQuery.size.width / 25,
          top: mediaQuery.size.height / 30,
          child: Container(
            child: Image.asset(
              'images/电视_on.png',
              width: mediaQuery.size.width / 5.5,
            ),
          ),
        ),
        Positioned(
          left: mediaQuery.size.width / 3.1,
          top: mediaQuery.size.height / 17,
          child: GestureDetector(
            child: Image.asset(
              bate[datas]['status'] == 'off'
                  ? 'images/off.png'
                  : 'images/on.png',
              width: mediaQuery.size.width / 15,
            ),
            onTap: () {
              var da = 'rf/iotgw/' + bate[datas]['name'] + '/get';
              var ta = 'rf/iotgw/' + bate[datas]['name'] + '/set';
              // 延时1s执行返回
              if (bate[datas]['status'] == 'off') {
                Message(ta, 'on');
                Future.delayed(Duration(milliseconds: 200), () {
                  Message(da, '');

                  Future.delayed(Duration(milliseconds: 200), () {
                    print(status);
                    if (status == 'on') {
                      showToastOnSuccess(bate[datas]['nickName']);
                    } else {
                      showToastOnFail(bate[datas]['nickName']);
                    }
                    setState(() {
                      bate[datas]['status'] = status == '' ? 'off' : status;
                    });
                  });
                });
              } else {
                Message(ta, 'off');
                Future.delayed(Duration(milliseconds: 200), () {
                  Message(da, '');
                  Future.delayed(Duration(milliseconds: 200), () {
                    print(status);
                    if (status == 'off') {
                      showToastOffSuccess(bate[datas]['nickName']);
                    } else {
                      showToastOffFail(bate[datas]['nickName']);
                    }
                    setState(() {
                      bate[datas]['status'] = status == '' ? 'off' : status;
                    });
                  });
                });
              }
            },
          ),
        ),
        Positioned(
          left: bate[datas]['nickName'].toString().length >= 4
              ? mediaQuery.size.width / 4.2
              : mediaQuery.size.width / 3.6,
          top: mediaQuery.size.height / 40,
          child: Container(
            child: new Text(
              bate[datas]['nickName'],
              style: TextStyle(
                  fontFamily: '黑体',
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: Colors.black),
            ),
          ),
        ),
      ],
    );
  }

  _createGridViewItem4(datas) {
    return Stack(
      overflow: Overflow.visible,
      children: <Widget>[
        Container(
          child: Image.asset('images/电视_0029.png'),
        ),
        Positioned(
          left: mediaQuery.size.width / 18,
          top: mediaQuery.size.height / 30,
          child: Container(
            child: Image.asset(
              'images/电视_on.png',
              width: mediaQuery.size.width / 5.5,
            ),
          ),
        ),
        Positioned(
          left: mediaQuery.size.width / 3.1,
          top: mediaQuery.size.height / 17,
          child: GestureDetector(
            child: Image.asset(
              bate[datas]['status'] == 'off'
                  ? 'images/off.png'
                  : 'images/on.png',
              width: mediaQuery.size.width / 15,
            ),
            onTap: () {
              var da = 'rf/iotgw/' + bate[datas]['name'] + '/get';
              var ta = 'rf/iotgw/' + bate[datas]['name'] + '/set';
              // 延时1s执行返回
              if (bate[datas]['status'] == 'off') {
                Message(ta, 'on');
                Future.delayed(Duration(milliseconds: 200), () {
                Message(da, '');

                Future.delayed(Duration(milliseconds: 200), () {
                  print(status);
                  if (status == 'on') {
                    showToastOnSuccess(bate[datas]['nickName']);
                  } else {
                    showToastOnFail(bate[datas]['nickName']);
                  }
                  setState(() {
                    bate[datas]['status'] = status == '' ? 'off' : status;
                  });
                });
                });
              } else {
                Message(ta, 'off');
                Future.delayed(Duration(milliseconds: 200), () {
                Message(da, '');
                Future.delayed(Duration(milliseconds: 200), () {
                  print(status);
                  if (status == 'off') {
                    showToastOffSuccess(bate[datas]['nickName']);
                  } else {
                    showToastOffFail(bate[datas]['nickName']);
                  }
                  setState(() {
                    bate[datas]['status'] = status == '' ? 'off' : status;
                  });
                });
                });
              }
            },
          ),
        ),
        Positioned(
          left: bate[datas]['nickName'].toString().length >= 6
              ? mediaQuery.size.width / 4.2
              : mediaQuery.size.width / 3.6,
          top: mediaQuery.size.height / 40,
          child: Container(
            child: new Text(
              bate[datas]['nickName'],
              style: TextStyle(
                  fontFamily: '黑体',
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: Colors.black),
            ),
          ),
        ),
      ],
    );
  }
}

void showToastOffFail(data) {
  Fluttertoast.showToast(
      msg: data + '电视关闭失败！',
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.CENTER,
      timeInSecForIosWeb: 1);
}

void showToastOffSuccess(data) {
  Fluttertoast.showToast(
      msg: data + '电视关闭成功！',
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.CENTER,
      timeInSecForIosWeb: 1);
}

void showToastOnSuccess(data) {
  Fluttertoast.showToast(
      msg: data + '电视开启成功！',
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.CENTER,
      timeInSecForIosWeb: 1);
}

void showToastOnFail(data) {
  Fluttertoast.showToast(
      msg: data + '电视开启失败！',
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.CENTER,
      timeInSecForIosWeb: 1);
}

void LEDshowToastOnSuccess(data) {
  Fluttertoast.showToast(
      msg: data + '灯带操作成功！',
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.CENTER,
      timeInSecForIosWeb: 1);
}

void LEDshowToastOnFail(data) {
  Fluttertoast.showToast(
      msg: data + '灯带操作失败！',
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.CENTER,
      timeInSecForIosWeb: 1);
}

void onConnected() {
  print('连接成功');
}

// 连接断开
void onDisconnected() {
  print('连接断开');
}

// 订阅主题成功
void onSubscribed(String topic) {
  print('订阅主题$topic成功');
}

// 订阅主题失败
void onSubscribeFail(String topic) {
  print('订阅主题 $topic失败');
}

// 成功取消订阅
void onUnsubscribed(String topic) {
  print('成功取消$topic主题订阅');
}

// 收到 PING 响应
void pong() {
  print('收到 PING 响应');
}
